import Vue from "vue";
import axios from "axios";
import CONFIG from "@/config";

// 支持的方法
const methods = [
  "get",
  "head",
  "post",
  "put",
  "delete",
  "options",
  "patch",
  "form",
];
const paramsMethods = ["get", "delete"];
// 添加请求前缀
const API_PREFIX = CONFIG.BASE_API_URL;

// 允许携带cookie
axios.defaults.withCredentials = true;
axios.defaults.timeout = 20000;

class Api {
  constructor() {
    methods.forEach(
      (method) =>
        (this[method] = (path, data = {}, headers = {}, isFile, msg) =>
          new Promise((resolve, reject) => {
            this.doFetch(
              method,
              path,
              data,
              headers,
              resolve,
              reject,
              isFile,
              msg
            );
          }))
    );
  }

  doFetch(method, path, data, headers, resolve, reject, isFile, msg) {
    const isForm = method === "form";
    const formData = isForm ? new FormData() : null;
    if (isForm) {
      if (data && data.length > 0) {
        const paths = [];
        data.forEach((file) => {
          formData.append("file", file);
          paths.push(file.title);
        });
        formData.append("paths", paths.toString(","));
      } else {
        const dataKeys = Object.keys(data);
        for (const key of dataKeys) {
          formData.append(key, data[key]);
        }
      }
    }
    // 签名
    const signData = {
      method,
      rawData: data,
      sysCode: CONFIG.SYS_CODE,
      secret: CONFIG.SECRET,
      token: localStorage.get("token") || "1076158999937963954",
    };

    let config = {
      headers: {
        "Content-Type": isForm ? "multipart/form-data" : "application/json",
        "X-Req-UserId": "607990864366431090",
        "Mch-Class": "MERCHANT_M",
        "x-req-merchantuserid": "767584428365340751", //模拟登陆
        ...headers,
        ...signData,
      },
    };
    if (isFile) {
      config.responseType = "arraybuffer";
    }

    data =
      paramsMethods.indexOf(method) !== -1
        ? {
            params: data,
            ...config,
          }
        : data;
    const _path = path.indexOf("http") === 0 ? path : `${API_PREFIX}${path}`;

    axios[isForm ? "post" : method](
      _path,
      isForm ? formData : data,
      config,
      msg
    )
      .then(({ data }) => {
        if (isFile) {
          resolve(data);
        } else if (msg) {
          //弹窗提示传入的msg内容
          Vue.prototype.$message({
            message: msg,
            type: "success",
          });
          resolve(data.data);
        } else if (data.code === 200) {
          resolve(data.data);
        } else if (data.code === 5225 || data.code === 5223) {
          Vue.prototype.$mainService.logout();
        } else {
          // 逻辑错误，按实际业务需求处理，默认弹窗提示
          Vue.prototype.$message({
            message: data.message,
            type: "error",
          });
          reject(data);
        }
      })
      .catch(async (error) => {
        if (error.response?.status === 403) {
          reject("抱歉，您暂无权限");
        } else if (error.response) {
          reject("服务器繁忙，请稍后再试");
        } else {
          reject("断网了，请注意您的网络连接");
        }
      });
  }
}

const api = new Api();

export default api;
